<template>
  <el-dialog :title="`${rows?.id ? '编辑' : '新增'}组织机构`" width="700px" :model-value="modelValue" @close="commEvent.onClose">
    <el-form ref="formRef" :model="formValue" :rules="rules">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属组织" prop="pid">
            <el-tree-select v-model="formValue.pid" :data="pidOption" check-strictly placeholder="请选择所属组织" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="组织名称" prop="organName">
            <el-input v-model="formValue.organName" placeholder="请输入组织名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人" prop="personCharge">
            <el-input v-model="formValue.personCharge" placeholder="请输入负责人姓名" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="commEvent.onClose">取消</el-button>
      <el-button type="primary" @click="commEvent.onSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, nextTick, PropType, ref, watch } from "vue"
import { ElMessage, FormInstance, FormRules } from "element-plus"
import { saveOrgan } from "@/api/modules/system"
import { SystemSpace } from "@/api/interface/system"

const props = defineProps({
  modelValue: Boolean,
  trees: { type: Array as PropType<SystemSpace.OrganTree[]>, defautl: () => [] },
  rows: { type: Object as PropType<SystemSpace.OrganTree>, defautl: () => {} }
})
const emit = defineEmits(["update:modelValue", "refresh"])
// 参数
const formRef = ref<FormInstance>() // 表单实例
const level = ref<number>(0) // 等级
// 表单数据
const formValue = ref({
  pid: undefined as undefined | number,
  organName: "",
  personCharge: ""
})
//  表单校验
const rules: FormRules = {
  pid: [{ required: true, message: "请选择所属组织", trigger: "change" }],
  organName: [{ required: true, message: "请输入组织名称", trigger: "blur" }],
  personCharge: [{ required: true, message: "请输入负责人姓名", trigger: "blur" }]
}
const pidOption = computed(() => commEvent.formatTrees(props.trees))
// 事件集合
const commEvent = {
  // 关闭弹窗
  onClose: () => {
    emit("update:modelValue", false)
  },
  formatTrees: (data?: SystemSpace.OrganTree[]): any[] => {
    if (!data || data.length <= 0 || data.some(item => item.level === 2)) return []
    return data.map(item => ({
      label: item.organName,
      value: item.id,
      disabled: props?.rows && props.rows.level - 1 !== item.level,
      children: commEvent.formatTrees(item.childrenTree)
    }))
  },
  getLevel: (data: SystemSpace.OrganTree[], id: number) => {
    data.forEach(item => {
      if (item.id === id) {
        level.value = item.level + 1
      } else {
        if (item?.childrenTree && item.childrenTree.length > 0) {
          commEvent.getLevel(item.childrenTree, id)
        }
      }
    })
  },
  // 确定
  onSubmit: () => {
    if (!formRef.value) return
    formRef.value.validate(async valid => {
      if (!valid) return
      const { pid } = formValue.value
      commEvent.getLevel(props.trees || [], Number(pid))
      const params: SystemSpace.SaveOrgan = { ...formValue.value, pid: Number(pid), level: level.value }
      if (props.rows?.id) {
        params.id = props.rows.id
      }
      const { code } = await saveOrgan(params)
      if (code !== "200") return
      ElMessage.success("操作成功")
      commEvent.onClose()
      emit("refresh")
    })
  }
}
watch(
  () => props.modelValue,
  val => {
    if (val) {
      nextTick(() => {
        if (!formRef.value) return
        formRef.value.resetFields()
        if (props.rows?.id) {
          const { pid, organName, personCharge } = props.rows
          formValue.value = { pid, organName, personCharge }
        }
      })
    }
  }
)
</script>

<style lang="scss" scoped></style>
